package tool

import (
	"encoding/json"
	"fmt"
	"io"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/duke-git/lancet/v2/netutil"
	"golang.org/x/text/encoding/simplifiedchinese"
)

// GetCityByIp 获取ip所属城市
func GetCityByIp(ip string) string {
	if ip == "" {
		return ""
	}

	if ip == "[::1]" || ip == "127.0.0.1" {
		return "内网IP"
	}

	url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
	resp, err := netutil.HttpGet(url, map[string]string{
		"Content-Type": "application/json",
	})
	if err != nil {
		return ""
	}
	bytes, _ := io.ReadAll(resp.Body)

	src := string(bytes)
	tmp, err := simplifiedchinese.GBK.NewDecoder().String(src)
	if err != nil {
		return ""
	}

	dataMap := make(map[string]interface{})
	err = json.Unmarshal([]byte(tmp), &dataMap)
	if err != nil {
		return ""
	}

	code, _ := convertor.ToInt(dataMap["code"])
	if code == 0 {
		city := fmt.Sprintf("%s %s", convertor.ToString(dataMap["pro"]), convertor.ToString(dataMap["city"]))
		return city
	}
	return ""
}
